package com.ctshk.common.utils;

import com.alibaba.nacos.common.utils.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * SIGN_KEY  = "1d70b9997df4946824810ebb069dbe28";  长隆解密KEY
 * */
public class APIAesUtil {
    /**
     * aes加密，密文是base64编码
     */
    public static String aesEncodeBase64(String data, String key) {
        return aesBase64(data, key, true);
    }

    /**
     * aes加密或解密，密文是base64编码
     */
    public static String aesBase64(String data, String key, boolean encodeMode) {
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            return null;
        }

        try {
            String KEY_AES = "AES", defaultCharset = "UTF-8", CIPHER_IALGORITHM = "AES/ECB/PKCS5Padding";
            byte[] content;
            if (encodeMode) {
                content = data.getBytes(defaultCharset);
            } else {
                content = decodeBase64(data);
            }
            // MD5后取16位
            key = DigestUtils.md5Hex(key.getBytes()).substring(8, 24);

            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(defaultCharset), KEY_AES);
            Cipher cipher = Cipher.getInstance(CIPHER_IALGORITHM);
            cipher.init(encodeMode?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE, keySpec);
            byte[] result = cipher.doFinal(content);
            if(encodeMode) {
                return encodeBase64(result);
            } else {
                return new String(result, defaultCharset);
            }
        } catch(Exception e) {
            return null;
        }
    }

    /**
     * 解码Base64字符串
     * @param message
     * @return
     */
    public static byte[] decodeBase64(String message) {
        return Base64.decodeBase64(message);
    }

    /**
     * 生成Base64字符串
     */
    public static String encodeBase64(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * aes解密，密文是base64编码
     */
    public static String aesDecodeBase64(String data, String key) {
        return aesBase64(data, key, false);
    }

}
